package edu.upenn.cis542;
import java.text.DecimalFormat;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class LightControllerActivity extends Activity {
	/** Called when the activity is first created. */
	static HttpURLConnection urlConnection;
	String params;
	private boolean state=false ;
	private boolean flag ;
	private boolean degC=true;
	Timer timer= new Timer();
	Timer timer1= new Timer();
	RadioButton myOption1, myOption2;
	private boolean connected = false;
	private boolean note =false;
	private boolean note1 =false;
	private boolean sensState = true;
	boolean val=false;
	Button click,clicknext,myOption3,thresh;
	String str ;
	TextView tvt,tvl,tvv;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		myOption1 = (RadioButton)findViewById(R.id.temp2);
		myOption2 = (RadioButton)findViewById(R.id.temp1);
		click = (Button)findViewById(R.id.click);
		thresh =(Button)findViewById(R.id.stand_by);
		click.setOnClickListener(connectListener);
		thresh.setOnClickListener(threshListener);
		myOption1.setOnClickListener(myOptionOnClickListener);
		myOption2.setOnClickListener(myOptionOnClickListener);
		myOption3 = (Button)findViewById(R.id.graph_display);
		//	myOption3.setOnClickListener(Listener);
		//alert();
		//timer.scheduleAtFixedRate(new TimerTask() {
		//public void run() {

		Thread cThread3 = new Thread(new ClientThread2());
		cThread3.start();
		//}
		//}, 5000, 10000);

		timer1.scheduleAtFixedRate(new TimerTask() {
			public void run() {

				handleConnectivity() ;
				}
			    }, 5000, 10000);




	}

	//		updateStatus(params);


	protected Dialog onCreateDialog(){
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Set Threshold");
		alert.setMessage("Enter the threshold temp in \u2103");

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				tvv = (TextView)findViewById(R.id.thresh);
				tvv.setText(input.getText().toString()+"\u2103");
				alert();

			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				// Canceled.
			}
		});
		alert.show();

		return null;


	}


	public void HandleButtons(){
		DecimalFormat df = new DecimalFormat("00.00");


		if (myOption1.isChecked() )
		{TextView t = (TextView)findViewById(R.id.temp); 	
		String txt = t.getText().toString();
		int length = txt.length();
		double temp=Double.parseDouble(txt.substring(0, (length-1)));
		double conv= (temp-32)*5/9 ;
		degC=true;
		String dispTemp = df.format(conv);
		t.setText(dispTemp+"\u2103");
		myOption1.setEnabled(false);
		myOption2.setEnabled(true);
		System.out.println("conv temp "+temp);
		}
		else 
		{
			if (myOption2.isChecked())
			{TextView t = (TextView)findViewById(R.id.temp); 	
			String txt = t.getText().toString();
			int length = txt.length();
			double temp  = Double.parseDouble(txt.substring(0, (length-1)));
			double conv= temp * 9/5 + 32 ;
			String dispTemp = df.format(conv);
			t.setText(dispTemp+"\u2109"); 
			degC=false;
			myOption2.setEnabled(false);
			myOption1.setEnabled(true);
			System.out.println("conv temp "+temp);
			}
		}

	}

	RadioButton.OnClickListener myOptionOnClickListener =
			new RadioButton.OnClickListener()
	{
		public void onClick(View v) {
			HandleButtons();
		} 
	};


	private OnClickListener connectListener = new OnClickListener() {

		public void onClick(View v) {
			togglebutton();
			alert();
			// connected=false;
		}

	};

	private OnClickListener threshListener = new OnClickListener() {

		public void onClick(View v) {
			updateSensorButton();
			//alert();
			// connected=false;
		}

	};
	//    private OnClickListener Listener = new OnClickListener() {
	//
	//        public void onClick(View v) {
	//        	alert();
	//        	//alert();
	//                   // connected=false;
	//            }
	//        
	//    };
	//    

	private void togglebutton(){
		if (!state){
			click.setText(" Switch Off");
			Thread cThread2 = new Thread(new ClientThread());
			cThread2.start();
			//               
			state=true;
		}
		else {
			click.setText("Switch On");

			Thread cThread = new Thread(new ClientThread());
			cThread.start();

			state=false;
		}
	}

	public class ClientThread implements Runnable {

		public void run() {
			try {
				Log.d("ClientActivity", "C: Connecting...");
				Socket socket = new Socket("192.168.170.143", 1234);
				connected = true;
				while (connected) {
					try {
						Log.d("ClientActivity", "C: Sending command.");
						// out = new PrintWriter(echoSocket.getOutputStream(), true);
						PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
						if (state==false)
						{
							out.println("off");connected = false;
							//flag=true;
						}
						else if (state==true)
						{
							out.println("on");connected = false;
							// flag = false;
						}
						out.flush();
						Log.d("ClientActivity", "C: Sent.");
					} catch (Exception e) {
						Log.e("ClientActivity", "S: Error", e);
					}
				}
				socket.close();
				// connected=false;
				Log.d("ClientActivity", "C: Closed.");
			} catch (Exception e) {
				Log.e("ClientActivity", "C: Error", e);
			}


		}

	}


	public class ClientThread2 implements Runnable {

		public void run() {
			try{
				DecimalFormat df1 = new DecimalFormat("00.00");
				Socket client = new Socket(("192.168.170.143"), 1234);
				PrintWriter out=null;
				BufferedInputStream in = null;
				out = new PrintWriter(client.getOutputStream(), true);
				in = new BufferedInputStream(client.getInputStream()); 
				byte[] b = new byte[1024];  
				int i = in.read(b);  
				str = new String(b, 0, i);  
				System.out.println("RECEIVE MESSAGE "+str);
				//if (str==null)
				//val = false;
				//else val=true;
				//System.out.println(sb.toString());
				//String str = sb.toString();
				StringTokenizer stk = new StringTokenizer(str, "\"");
				String [] status = new String[5];
				int i1 =0;
				while(stk.hasMoreTokens()){
					status[i1] = stk.nextToken();
					i1++;
				}
				System.out.println(status.length);
				if(status.length<4){
					System.out.println("Wrong number of arguments");
					return;
				}
				else{
					String temp = status[1];
					String light = status[3];
					tvt = (TextView)findViewById(R.id.temp);
					String dispTemp1 = df1.format(temp);
					temp = dispTemp1 + "\u2103";
					tvt.setText(temp);

					tvl = (TextView)findViewById(R.id.light);
					String dispLight = df1.format(light);
					tvl.setText(dispLight);

					System.out.println(temp+" "+dispLight);
					if(light.equals("on"))
						state=false;
					else
						state=true;
					//updateLightButton(flag);
					togglebutton();

				}

				in.close();
				out.close();
				client.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}

	}
	private void updateLightButton(boolean flag2) {

		if(flag2){
			Button b =(Button)findViewById(R.id.click);
			b.setText(getResources().getString(R.string.on));
		}
		else{
			Button b =(Button)findViewById(R.id.click);
			b.setText(getResources().getString(R.string.off));
		}
	}


	public void setThreshold(View view){
		onCreateDialog();
		//alert();

	}

	public void alert()
	{   
		double compare;
		if (degC==true)
		{
		TextView comp = (TextView)findViewById(R.id.temp);
		String text=comp.getText().toString();
		int length = text.length();
		double val1=Double.parseDouble(text.substring(0, (length-1)));
		System.out.println(val1);
		compare=val1;
		}
		else
		{
		TextView comp = (TextView)findViewById(R.id.temp);
		String text=comp.getText().toString();
		int length = text.length();
		double val2=Double.parseDouble(text.substring(0, (length-1)));
		double val3= (val2-32)*5/9;
		System.out.println(val3);
		compare=val3;
		}

		TextView comp1=(TextView)findViewById(R.id.thresh);
		String text1=comp1.getText().toString();
		int length1 = text1.length();
		double val2=Double.parseDouble(text1.substring(0, (length1-1)));
		System.out.println(val2);
		//int val1 = Integer.parseInt((String) tvt.getText());
		//int val2 = Integer.parseInt(tvv.getText().toString());
		if(compare>val2)
		{


//Notification Title and Message
                    Notification("Important message", "Temperature is above threshold!!!!");

        }




		else 
		{
			System.out.println("hello");
		}

	}




	public class ClientThread4 implements Runnable {

		public void run() {



			try {
				Log.d("ClientActivity", "C: Connecting...");
				Socket socket = new Socket("192.168.170.143", 1234);
				//connected = true;
				//while (connected) {
				try {
					Log.d("ClientActivity", "C: Sending command.");
					// out = new PrintWriter(echoSocket.getOutputStream(), true);
					PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
					if (sensState==false)
					{
						out.println("sleep");//connected = false;
						//flag=true;
					}
					else if (sensState==true)
					{
						out.println("resume");//connected = false;
						// flag = false;
					}
					out.flush();
					Log.d("ClientActivity", "C: Sent.");
				} catch (Exception e) {
					Log.e("ClientActivity", "S: Error", e);
				}
				//}
				socket.close();
				// connected=false;
				Log.d("ClientActivity", "C: Closed.");
			} catch (Exception e) {
				Log.e("ClientActivity", "C: Error", e);
			}
		}

	}

	private void updateSensorButton() {

		if (!sensState){
			thresh.setText("StandBy");
			Thread cThread4 = new Thread(new ClientThread4());
			cThread4.start();
			//               
			sensState=true;
		}
		else {
			thresh.setText("Resume");

			Thread cThread = new Thread(new ClientThread4());
			cThread.start();

			sensState=false;
		}
	}

	public void onQuit(View view){
		finish();
	}



	//	private void Notification(String string, String string2) {
	//		// TODO Auto-generated method stub
	//		
	//	}
	  

	  @SuppressWarnings("deprecation")
		public void Notification(String notificationTitle, String notificationMessage) {
			  
				   	     
			   final int NOTIFICATION_ID = 1;
			    		String ns = Context.NOTIFICATION_SERVICE;
			    		NotificationManager manager =(NotificationManager) getSystemService(ns);
			    		int icon = R.drawable.ic_launcher;
			    		CharSequence tickerText = "Alert!"; // text at top
			    		long when = System.currentTimeMillis();
			    		
			    		Notification notification = new Notification(icon,
			  															 tickerText, when);
			    		Context context = getApplicationContext();
			    		Intent notificationIntent = new Intent(this,
			   															this.getClass());
			    		PendingIntent contentIntent =PendingIntent.getActivity(
			  											this, 0, notificationIntent, 0);
			    
			    		notification.setLatestEventInfo(context, notificationTitle,
			    				notificationMessage, contentIntent);
			   
			      		manager.notify(NOTIFICATION_ID, notification);
			     

				     
	}

		  @SuppressWarnings("deprecation")
		public void handleConnectivity() {
		  ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	  if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED 
	      ||  conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
	      //notify user you are not online


	    	 final int NOTIFICATION_ID = 2;
	    		String ns = Context.NOTIFICATION_SERVICE;
	    		NotificationManager manager =(NotificationManager) getSystemService(ns);
	    		int icon = R.drawable.ic_launcher;
	    		CharSequence tickerText = "Alert!"; // text at top
	    		long when = System.currentTimeMillis();
	    
	    		
	    		Notification notification = new Notification(icon,
	  															 tickerText, when);
	    		Context context = getApplicationContext();
	    		CharSequence contentTitle = "Important message"; // title
	    		CharSequence contentText = "Connectivity Lost"; // message
	    		//CharSequence contentText1 = "No Connectivity"; 
	    		Intent notificationIntent = new Intent(this,
	   															this.getClass());
	    		PendingIntent contentIntent =PendingIntent.getActivity(
	  											this, 0, notificationIntent, 0);
	    if(note==false)
	    {
	    		notification.setLatestEventInfo(context, contentTitle,
	    				contentText, contentIntent);
	    		manager.notify(NOTIFICATION_ID, notification);
	    		note = true;
	    		 note1=false;}
	   
	    else 
	    {
	    	 System.out.println("No Connectivity"); 
	      	    note =true;
	    }
}
	  else
		  
		  if(note==true && note1==false)
		  {
			  final int NOTIFICATION_ID = 4;
	    		String ns = Context.NOTIFICATION_SERVICE;
	    		NotificationManager manager =(NotificationManager) getSystemService(ns);
	    		int icon = R.drawable.ic_launcher;
	    		CharSequence tickerText = "Alert!"; // text at top
	    		long when = System.currentTimeMillis();
	    
	    		
	    		Notification notification = new Notification(icon,
	  															 tickerText, when);
	    		Context context = getApplicationContext();
	    		CharSequence contentTitle = "Important message"; // title
	    		CharSequence contentText = "Connectivity regained"; // message
	    		//CharSequence contentText = "No Connectivity"; 
	    		Intent notificationIntent = new Intent(this,
	   															this.getClass());
	    		PendingIntent contentIntent =PendingIntent.getActivity(
	  											this, 0, notificationIntent, 0);
	    		
	    		notification.setLatestEventInfo(context, contentTitle,
	    				contentText, contentIntent);
	    		manager.notify(NOTIFICATION_ID, notification);
	    		note1=true;
	    		note = false;
		  }
		  
				
		  else
		  {
			  System.out.println("in else");
		  }
		  
		  
		  }  

}